# -*- coding: utf-8 -*-
import logging
import string
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to, redirect
from pylons.decorators import jsonify
from pylons.decorators import validate
from authkit.authenticate import valid_password
import formencode
from sqlalchemy.sql import update
from pythonblog.lib.base import BaseController, render
from pythonblog import model
from pythonblog.model.account import *
from pythonblog.controllers import custom_formatter, captchas, UserProfileForm, preservedNames
from pythonblog.service import user_service
import pythonblog.lib.helpers as h


log = logging.getLogger(__name__)

    
class AccountController(BaseController):

    @jsonify
    def log_in(self):      
        userName = request.params.getone('userName')
        password = request.params.getone('password')
        if not valid_password(request.environ, userName, password):
            return { 'flag': 0, 'info': u"登录失败：用户密码不匹配" }
        user_service.update_user_login_date(userName)
        request.environ['paste.auth_tkt.set_user'](userid=userName)
        remember_me = request.params.get('remember_me')
        if (remember_me and remember_me == 'true'):
            self._set_cookie('logined_id', userName)
        t =   u"""<div>欢迎您，<span id="userName">%s</span>！<a href="%s">退出</a></div>
        <div>您可以登录您的专区发表文章：<a href="%s">我的专区</a></div>"""\
        %(user_service.get_user(userName).author, h.url_for_www(controller='account', action='log_out', section_id=request.params.get('section_id')),
          h.url_for('home', sub_domain=userName))
        return { 'flag': 1, 'info': t } 
    
    def log_out(self):
        self._delete_cookie('logined_id')
        request.environ['paste.auth_tkt.logout_user']()
        redirect(request.params.get('url'))
    
    def register(self):
        self._set_menu()
        c.random = captchas.random()
        c.captcha_img = self._get_captchas_img()
        return render('/derived/account/register.html')

    def _get_captchas_img(self):
        return h.literal(string.replace(string.replace(captchas.image(), '<a href="http://captchas.net">', '<a>'), 'alt="The CAPTCHA image"', ''))

    """
    @validate(schema=UserProfileForm(), form='register', post_only=False, 
              on_get=True, auto_error_formatter=custom_formatter)
              
              """
    def create(self):
        self._set_menu()
        schema = UserProfileForm()
        try:
            c.form_result = schema.to_python(dict(request.params))
        except formencode.Invalid, error:
            c.form_result = error.value
            c.form_result['random'] = captchas.random()
            c.captcha_img = self._get_captchas_img()
            c.form_errors = error.error_dict or {}
            html = render('/derived/account/register.html')
            return formencode.htmlfill.render(
                html,
                defaults=c.form_result,
                errors=c.form_errors,
                auto_error_formatter=custom_formatter
                )
        else:
            userName = c.form_result['userName']
            users = request.environ['authkit.users']
            users.user_create(userName, password=c.form_result['password'])
            users.user_add_role(userName, role="user")

            user = UserProfile()
            user.userName = userName.lower()
            user.realName =  c.form_result['realName']
            user.gender = c.form_result['gender']
            email = c.form_result['email']
            if not email:
                user.email = None
            else:
                user.email = email
            user.city = c.form_result['city']
            user.vocation = c.form_result['vocation']
            user.industry = c.form_result['industry']
            user.loginDate = h.now()
            meta.Session.add(user)

            meta.Session.commit()
            request.environ['paste.auth_tkt.set_user'](userid=userName)
            user_service.add_or_update_to_cache(user)
            redirect(h.url_for('home', sub_domain=userName))
    
    def validateUserName(self):
        userName = request.params.get('userName')
        if not userName:
            return 'false'
        if userName in preservedNames:
            return 'false'
        
        if user_service.is_user_exist(userName):
            return 'false'
        return 'true'
    
    def validateEmail(self):
        email = request.params.get('email')
        if not email:
            return 'true'
        if user_service.is_email_repeat(email):
            return 'false'
        return 'true'
    
    def validateEmailUpdate(self):
        email = request.params.get('email')
        if not email:
            return 'true'
        userName = request.params.getone('userName')
        if user_service.is_email_repeat(email, userName):
            return 'false'
        return 'true'
    
    def help(self):
        return "help page"
    
